package com.leo.erp.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.AccountItemMapper;
import com.leo.erp.dao.InOutItemMapper;
import com.leo.erp.dto.InOutItemExecution;
import com.leo.erp.entity.AccountItem;
import com.leo.erp.entity.InOutItem;
import com.leo.erp.entity.User;
import com.leo.erp.enums.InOutItemStateEnum;
import com.leo.erp.service.InOutItemService;
import com.leo.erp.service.LogService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.StringUtil;

@Service
public class InOutItemServiceImpl implements InOutItemService{
	@Autowired
	private InOutItemMapper inOutItemMapper;
	@Autowired
	private AccountItemMapper accountItemMapper;
	@Autowired
	private LogService logService;

	@Override
	public InOutItemExecution findBySelect(String type) {
		InOutItemExecution ie = new InOutItemExecution();
		QueryWrapper<InOutItem> queryWrapper = new QueryWrapper<>();
		if(type.equals("in")) {
			queryWrapper.eq("type", "收入");
			queryWrapper.ne("deleteFlag", "1");
		}else if(type.equals("out")) {
			queryWrapper.eq("type", "支出");
			queryWrapper.ne("deleteFlag", "1");
		}
		queryWrapper.orderByDesc("inOutItemId");
		try {
			List<InOutItem> list = inOutItemMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				ie.setState(InOutItemStateEnum.SUCCESS.getState());
				ie.setInOutItemList(list);
			}else {
				ie.setState(InOutItemStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ie;
	}
	
	/**
	 * 正常删除，要考虑数据完整性，进行完整性校验
	 */
	@Override
	@Transactional
	public InOutItemExecution batchDeleteInOutItemByIdsNormal(String ids) {
		InOutItemExecution ie = new InOutItemExecution();
		/**
         * 校验
         * 1、财务子表	tb_account_item
         * 是否有相关数据
         * */
		if(StringUtil.isEmpty(ids)) {
			ie.setState(InOutItemStateEnum.OFFLINE.getState());
			return ie;
		}
		
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		
		/**
         * 校验财务子表	tb_account_item
         * */
		try {
			QueryWrapper<AccountItem> queryAccountItem = new QueryWrapper<>();
			queryAccountItem.in("inOutItemId", idList);
			List<AccountItem> accountItemList = accountItemMapper.selectList(queryAccountItem);
			if(accountItemList.size() > 0) {
				//有数据,可以执行强制删除
				ie.setState(InOutItemStateEnum.DELETE.getState());
				return ie;
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
         * 校验通过执行删除操作
         * */
		int effectedNum = batchDeleteInOutItemByIds(ids);
		if(effectedNum > 0) {
			ie.setState(InOutItemStateEnum.SUCCESS.getState());
		}else {
			ie.setState(InOutItemStateEnum.OFFLINE.getState());
		}
		
		return ie;
	}

	@Transactional
	@Override
	public int batchDeleteInOutItemByIds(String ids) {
		StringBuffer sb = new StringBuffer();
		List<Long> idList = StringUtil.strToLongList(ids);
		QueryWrapper<InOutItem> queryInOutItem = new QueryWrapper<>();
		queryInOutItem.in("inOutItemId", idList);
		List<InOutItem> list = inOutItemMapper.selectList(queryInOutItem);
		for(InOutItem inOutItem : list) {
			sb.append("[").append(inOutItem.getName()).append("]");
		}
		logService.insertLog("收支项目", sb.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		int effectedNum = 0;
		try {
			InOutItem inOutItem = new InOutItem();
			inOutItem.setDeleteFlag("1");
			inOutItem.setTenantId(user.getUserId());
			UpdateWrapper<InOutItem> updateWrapper = new UpdateWrapper<>();
			updateWrapper.in("inOutItemId", idList);
			effectedNum = inOutItemMapper.update(inOutItem, updateWrapper);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return effectedNum;
	}

	@Override
	@Transactional
	public InOutItemExecution insertInOutItem(String beanJson, HttpServletRequest request) throws GlobalRuntimeException{
		InOutItemExecution ie = new InOutItemExecution();
		InOutItem inOutItem = JSONObject.parseObject(beanJson, InOutItem.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		inOutItem.setTenantId(user.getUserId());
		try {
			int effectedNum = inOutItemMapper.insert(inOutItem);
			if(effectedNum > 0) {
				logService.insertLog("收支项目", "新增:" + inOutItem.getName(), request);
				ie.setState(InOutItemStateEnum.SUCCESS.getState());
			}else {
				ie.setState(InOutItemStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ie;
	}

	@Override
	public InOutItemExecution updateInOutItem(String beanJson, int inOutItemId, HttpServletRequest request) {
		InOutItemExecution ie = new InOutItemExecution();
		InOutItem inOutItem = JSONObject.parseObject(beanJson, InOutItem.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		inOutItem.setTenantId(user.getUserId());
		inOutItem.setInOutItemId(inOutItemId);
		try {
			int effectedNum = inOutItemMapper.updateById(inOutItem);
			if(effectedNum > 0) {
				logService.insertLog("收支项目", "修改:" + inOutItem.getName().toString(), request);
				ie.setState(InOutItemStateEnum.SUCCESS.getState());
			}else {
				ie.setState(InOutItemStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ie;
	}

	@Override
	public InOutItemExecution checkIsNameExist(int inOutItemId, String name) {
		InOutItemExecution ie = new InOutItemExecution();
		QueryWrapper<InOutItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("inOutItemId", inOutItemId);
		queryWrapper.eq("name", name);
		queryWrapper.ne("deleteFlag", "1");
		try {
			List<InOutItem> list = inOutItemMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				ie.setState(InOutItemStateEnum.SUCCESS.getState());
			}else {
				ie.setState(InOutItemStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ie;
	}

	@Override
	public InOutItemExecution getList(String name, String type, String remark, int currentPage, int pageSize) {
		InOutItemExecution ie = new InOutItemExecution();
		QueryWrapper<InOutItem> queryWrapper = new QueryWrapper<>();
		
		//判断
		if(name != null && name != "") {
			queryWrapper.like("name", name);
		}
		if(type != null && type != "") {
			queryWrapper.like("type", type);
		}
		if(remark != null && remark != "") {
			queryWrapper.like("remark", remark);
		}
		queryWrapper.ne("deleteFlag", "1");
		
		Page<InOutItem> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = inOutItemMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			ie.setState(InOutItemStateEnum.SUCCESS.getState());
			ie.setPages(page.getPages());//总页数
			ie.setTotal(iPage.getTotal());//总记录数
			ie.setInOutItemPageList(iPage.getRecords());
		}else{
			ie.setState(InOutItemStateEnum.OFFLINE.getState());
		}
		
		return ie;
	}
	
	
}
